# coding=utf-8
from selenium import webdriver
from selenium.webdriver import DesiredCapabilities

from core.m_logging import logger
from core.response import Response


class SeleniumRequest(object):
    driver = None
    driver_reuse_count = 1000
    _driver_used_count = 0

    def __init__(self, url, method="GET", engine_name="CHROME"):
        self.middleware_list = []
        self.method = method
        self.url = url
        self.proxies = None
        self.header = None
        self.engine_name = engine_name
        # self.driver_reuse_count = 0
        # self.driver = None

    def request(self):
        for m in self.middleware_list:
            m.process(self)
        if SeleniumRequest._driver_used_count % SeleniumRequest.driver_reuse_count == 0:
            logger.info("re-init driver since the re-use count is just started or reached %s..." % SeleniumRequest.driver_reuse_count)
            SeleniumRequest._driver_used_count += 1
            SeleniumRequest.driver = SeleniumDriver('CHROME', self.header)
            # SeleniumRequest.driver = d.driver

        logger.info("request to %s..." % self.url)
        SeleniumRequest.driver.get(self.url)
        response = Response(self.url, status_code=200, encoding="utf-8", content=SeleniumRequest.driver.content)

        logger.info("status done...")
        return response

    def middleware(self, middleware):
        self.middleware_list.append(middleware)
        return self


class SeleniumDriver(object):
    def __init__(self, engine_name, headers):
        if engine_name == "CHROME":
            self.driver = self._init_chrome_driver(headers)
        elif engine_name == "FIREFOX":
            self.driver = self._init_firefox_driver(headers)
        else:
            self.driver = self._init_phantomjs_driver(headers)

    def get(self, url):
        self.driver.get(url)

    @property
    def content(self):
        return self.driver.page_source

    @staticmethod
    def _init_chrome_driver(headers):
        logger.info("chrome (headless mode) is starting. required chrome version above 59...")
        from selenium.webdriver.chrome.options import Options
        chrome_options = Options()
        chrome_options.add_argument('--headless')
        chrome_options.add_argument('--disable-gpu')
        for k, v in headers.items():
            chrome_options.add_argument('%s="%s"' % (k, v))
        # chrome_options.add_argument(
        #     'user-agent="Mozilla/5.0 (iPod; U; CPU iPhone OS 2_1 like Mac OS X; ja-jp) AppleWebKit/525.18.1 (KHTML, like Gecko) Version/3.1.1 Mobile/5F137 Safari/525.20"')
        driver = webdriver.Chrome(chrome_options=chrome_options)
        driver.set_page_load_timeout(60)
        return driver

    @staticmethod
    def _init_firefox_driver(headers):
        logger.info("firefox is starting...")
        driver = webdriver.Firefox()
        driver.set_page_load_timeout(60)
        return driver

    @staticmethod
    def _init_phantomjs_driver(headers):
        logger.info("phantomJs is starting...")
        caps = DesiredCapabilities.PHANTOMJS
        caps["phantomjs.page.settings.resourceTimeout"] = 60000  # timeout after 60s
        caps["phantomjs.page.settings.loadImages"] = False  # 不载入图片，爬页面速度会快很多
        # caps["phantomjs.page.settings.userAgent"] = user_agent
        driver = webdriver.PhantomJS()  # 指定使用的浏览器
        driver.set_page_load_timeout(60)
        return driver

    # def _init_selenium_driver(self, user_agent, engine_name):
    #     if engine_name == "CHROME":
    #         return self._init_chrome_driver(user_agent)
    #     elif engine_name == "FIREFOX":
    #         return self._init_firefox_driver(user_agent)
    #     else:
    #         return self._init_phantomjs_driver(user_agent)
